package com.example.weather.myframe;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.ContentUris;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;


/**
 * <p>
 * 选择照片<br/>
 * 在Manifest中添加两个Activity标签<br/>
 * 1、<br/>
 <activity
 android:name="com.example.weather.myframe.PopupSelectImage"
 android:theme="@style/style_window_showmenu" />
 <activity android:name="com.example.weather.myframe.CropImageActivity"/>



 * //onActivityResult中的resultCode值为{@linkConstants.SELECT_IMAGE}
 *
 * @author Zero @date 2014-2-17<br>
 * @version 1.0<br>
 */
public class PopupSelectImage extends Activity {
	private static final int REQUEST_CODE_FOLDER = 1006;
	private static final int REQUEST_CODE_CAMERA = 1007;
//	private File file; // 缓存图片文件
	private Intent resultIntent;
	private Intent intent;
private static final int REQUEST_PICK_IMAGE = 1; //相册选取
	private static final int REQUEST_CAPTURE = 2;  //拍照
	private static final int REQUEST_PICTURE_CUT = 3;  //剪裁图片
	private Uri imageUri;//原图保存地址
	private String imagePath;
	private boolean isClickCamera;
	/**
	 * dsy
	 * 
	 * 为了判断是否是点击了拍照 false代表是相册 true代表相机
	 */
	private boolean isPai;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 竖屏锁定
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
//		 setTheme(R.style.style_window_showmenu);
		setContentView(R.layout.pop_selectimage);
		// 初始化数据

//
		// 初始化控件
//		 findViewById(R.id.pop_selectimage_linlay_content).setOnClickListener(
//		 this);
		resultIntent = getIntent();
		findViewById(R.id.pop_selectimage_btn_camera).setOnClickListener(new OnClickListener() {

			private Intent intent;

			@Override
			public void onClick(View v) {
				if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
					//////////////////// 三星手机 需要设置
					String mtype = android.os.Build.MANUFACTURER; // 手机型号
					if (!mtype.contains("samsung")) {
						openCamera();
						isClickCamera = true;
					}else {
						file=new File(FileManager.getCompressFilePath());
						file.mkdirs();
						file = new File(FileManager.getCompressFilePath() , System.currentTimeMillis() + ".jpg");
						if (!file.exists()) {
							File f = new File(FileManager.getSaveFilePath());// 获取缓存文件的路径
							if (!f.exists()) {// 文件不存在
								f.mkdirs();// 创建此抽象路径名指定的目录，包括所有必需但不存在的父目录
							}
							try {
								file.createNewFile();// 创建新文件
							} catch (IOException e) {
								e.printStackTrace();
								Toast.makeText(PopupSelectImage.this, "照片创建失败!", Toast.LENGTH_LONG).show();
								return;
							}
						}
						intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
						intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
						startActivityForResult(intent, REQUEST_CODE_CAMERA);
						isClickCamera = true;
					}
				} else {
					Toast.makeText(PopupSelectImage.this, "sdcard无效或没有插入!", Toast.LENGTH_LONG).show();
				}
			}
		});

		// 相册
		findViewById(R.id.pop_selectimage_btn_folder).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				String mtype = android.os.Build.MANUFACTURER; // 手机型号
				if (!mtype.contains("samsung")) {
					selectFromAlbum();
				}else {
//					file=new File(FileManager.getCompressFilePath());
//					file.mkdirs();
//					file = new File(FileManager.getCompressFilePath() , System.currentTimeMillis() + ".jpg");
//					Intent intent = new Intent(Intent.ACTION_PICK);
//					intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
////					intent.setType("image/*");
////					intent.setAction(Intent.ACTION_GET_CONTENT);
//					startActivityForResult(intent, REQUEST_CODE_FOLDER);
					selectFromAlbums();
				}
				isClickCamera = false;
			}
		});
		// 取消
		findViewById(R.id.pop_selectimage_btn_canle).setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
	}


	@Override
	public boolean onTouchEvent(MotionEvent event) {
		finish();
		return true;
	}

	@Override
	public void finish() {
		super.finish();
		overridePendingTransition(R.anim.push_bottom_out, 0);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode != RESULT_OK)
			return;
		switch (requestCode) {
			case REQUEST_PICK_IMAGE://从相册选择lizheng
				if (Build.VERSION.SDK_INT >= 19) {
					handleImageOnKitKat(data);
				} else {
					handleImageBeforeKitKat(data);
				}
				break;
			case REQUEST_CAPTURE://拍照lizheng
				/**
				 * dsy 为了判断是否是点击了拍照 false代表是相册 true代表相机
				 */
				if (resultCode == RESULT_OK) {
					if (isClickCamera==true) {
						File oldFile = null;
						try {
							oldFile = FileUtil.getTempFile(PopupSelectImage.this, imageUri);
						}catch (Exception e){}
						resultIntent.putExtra("file",setbitmaps(oldFile));// new File(imagePath));

//						resultIntent.putExtra("file", new File(file.getPath()));
						setResult(RESULT_OK, resultIntent);
						//Toast.makeText(this, "设置成功"+path, Toast.LENGTH_SHORT).show();
						finish();

					}

				}
				break;
			case REQUEST_PICTURE_CUT://裁剪完成
//                    if (isClickCamera==false)
//					{
//						resultIntent.putExtra("file", new File(imagePath));
//						/**
//						 * dsy 为了判断是否是点击了拍照 false代表是相册 true代表相机
//						 */
//						setResult(RESULT_OK, resultIntent);
//						//Toast.makeText(this, "设置成功"+path, Toast.LENGTH_SHORT).show();
//						finish();
//                    }
				break;
		case REQUEST_CODE_CAMERA:// 拍照daishuyu
			if (file != null && file.exists()) {
				if (FileManager.hasSDCard()) {
					String path = CompressionUtil.compressionBitmap(file.getAbsolutePath(),isPai);
					resultIntent.putExtra("file", new File(path));
					/**
					 * dsy 为了判断是否是点击了拍照 false代表是相册 true代表相机
					 */
					setResult(RESULT_OK, resultIntent);
					finish();
					isPai = true;
				} else {
					Toast.makeText(this, "未找到存储卡,无法存储照片", Toast.LENGTH_LONG).show();
				}
			}
			break;
		case REQUEST_CODE_FOLDER:// 相册daishuyu
			handleImageOnKitKat(data);

				isPai = false;
			break;
		case Crop.REQUEST_CROP:
//			handleCrop(resultCode, data);
			break;
		default:
			break;
		}
	}

	private File setbitmaps(File filePath) {
		return CompressHelper.getDefault(getApplicationContext()).compressToFile(filePath);

	}
	private File setbitmaps(String filePath) {
		return CompressHelper.getDefault(getApplicationContext()).compressToFile(new File(filePath));


//		BitmapFactory.Options options=new BitmapFactory.Options();
//		options.inSampleSize=4;
//		Bitmap bim = BitmapFactory.decodeFile(filePath, options);
//		FileOutputStream os = null;
//		try {
//            os = new FileOutputStream(filePath);
//            bim.compress(Bitmap.CompressFormat.JPEG, 90, os);
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }finally {
//            if (os!=null)
//                try {
//					os.flush();
//                    os.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//        }
	}




	// 开始裁剪daishuyu
	private void beginCrop(Uri source) {


//		new Crop(source).output(outputUri).asSquare().start(this);
	}

	// 保存裁剪之后的图片数据daishuyu
	private void handleCrop(int resultCode, Intent result) {
		if (resultCode == RESULT_OK) {
			String path = CompressionUtil.compressionBitmap(file.getAbsolutePath(),isPai);
			if (file.exists())
				file.delete();
			resultIntent.putExtra("file", new File(path));
			/**
			 * dsy 为了判断是否是点击了拍照 false代表是相册 true代表相机
			 */
			setResult(RESULT_OK, resultIntent);
			//Toast.makeText(this, "设置成功"+path, Toast.LENGTH_SHORT).show();
			finish();
		} else if (resultCode == Crop.RESULT_ERROR) {
			Toast.makeText(this, Crop.getError(result).getMessage(), Toast.LENGTH_SHORT).show();
		}
	}

	/**
	 * 打开系统相机
	 */
	private void openCamera() {
		 file = new FileStorage().createIconFile();
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {

			imageUri = FileProvider.getUriForFile(PopupSelectImage.this, "com.jbm.jbmsupplier.fileprovider", file);//通过FileProvider创建一个content类型的Uri

		} else {
			imageUri = Uri.fromFile(file);
		}
		Intent intent = new Intent();
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
			intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); //添加这一句表示对目标应用临时授权该Uri所代表的文件
		}
		intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);//设置Action为拍照
		intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);//将拍取的照片保存到指定URI
		startActivityForResult(intent, REQUEST_CAPTURE);
	}

	/**
	 * 从相册选择
	 */
	private void selectFromAlbum() {
		Intent intent = new Intent(Intent.ACTION_PICK);
		intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
		startActivityForResult(intent, REQUEST_PICK_IMAGE);
	}
	/**
	 * 从相册选择
	 */
	private void selectFromAlbums() {
		Intent intent = new Intent(Intent.ACTION_PICK);
		intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
		startActivityForResult(intent, REQUEST_CODE_FOLDER);
	}
	/**
	 * 裁剪
	 */
	File file;

	private void cropPhoto() {
		file = new FileStorage().createCropFile();
		Uri outputUri = Uri.fromFile(file);//缩略图保存地址
		Intent intent = new Intent("com.android.camera.action.CROP");
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
			intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
		}
		intent.setDataAndType(imageUri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("aspectX", 1);
		intent.putExtra("aspectY", 1);
		intent.putExtra("scale", true);
		intent.putExtra("return-data", false);
		intent.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);
		intent.putExtra("outputFormat", Bitmap.CompressFormat.PNG.toString());
		intent.putExtra("noFaceDetection", true);
		startActivityForResult(intent, REQUEST_PICTURE_CUT);
	}


	@TargetApi(19)
	private void handleImageOnKitKat(Intent data) {
		imagePath = null;
		imageUri = data.getData();
		if (DocumentsContract.isDocumentUri(this, imageUri)) {
			//如果是document类型的uri,则通过document id处理
			String docId = DocumentsContract.getDocumentId(imageUri);
			if ("com.android.providers.media.documents".equals(imageUri.getAuthority())) {
				String id = docId.split(":")[1];//解析出数字格式的id
				String selection = MediaStore.Images.Media._ID + "=" + id;
				imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
			} else if ("com.android.downloads.documents".equals(imageUri.getAuthority())) {
				Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
				imagePath = getImagePath(contentUri, null);
			}
		} else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
			//如果是content类型的Uri，则使用普通方式处理
			imagePath = getImagePath(imageUri, null);
		} else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
			//如果是file类型的Uri,直接获取图片路径即可
			imagePath = imageUri.getPath();
		}
		if (isClickCamera==false)
		{
			String mtype = android.os.Build.MANUFACTURER; // 手机型号
			if (mtype.contains("samsung")) {
				String path = CompressionUtil.compressionBitmap(imagePath,isPai);
				resultIntent.putExtra("file", new File(path));
			}else {
				File oldFile = null;
				try {
				 oldFile = FileUtil.getTempFile(PopupSelectImage.this, imageUri);
				}catch (Exception e){}
				resultIntent.putExtra("file",setbitmaps(oldFile));// new File(imagePath));
			}
			/**
			 * dsy 为了判断是否是点击了拍照 false代表是相册 true代表相机
			 */
			setResult(RESULT_OK, resultIntent);
			//Toast.makeText(this, "设置成功"+path, Toast.LENGTH_SHORT).show();
			finish();
		}
	}


//三星xiangce
	@TargetApi(19)
	private void handleImageOnKitKats(Intent data) {
		imagePath = null;
		imageUri = data.getData();
		if (DocumentsContract.isDocumentUri(this, imageUri)) {
			//如果是document类型的uri,则通过document id处理
			String docId = DocumentsContract.getDocumentId(imageUri);
			if ("com.android.providers.media.documents".equals(imageUri.getAuthority())) {
				String id = docId.split(":")[1];//解析出数字格式的id
				String selection = MediaStore.Images.Media._ID + "=" + id;
				imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);
			} else if ("com.android.downloads.documents".equals(imageUri.getAuthority())) {
				Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(docId));
				imagePath = getImagePath(contentUri, null);
			}
		} else if ("content".equalsIgnoreCase(imageUri.getScheme())) {
			//如果是content类型的Uri，则使用普通方式处理
			imagePath = getImagePath(imageUri, null);
		} else if ("file".equalsIgnoreCase(imageUri.getScheme())) {
			//如果是file类型的Uri,直接获取图片路径即可
			imagePath = imageUri.getPath();
		}

		String path = CompressionUtil.compressionBitmap(imagePath,isPai);
		if (isClickCamera==false)
		{

			resultIntent.putExtra("file", new File(path));
			/**
			 * dsy 为了判断是否是点击了拍照 false代表是相册 true代表相机
			 */
			setResult(RESULT_OK, resultIntent);
			//Toast.makeText(this, "设置成功"+path, Toast.LENGTH_SHORT).show();
			finish();
		}
	}







	private void handleImageBeforeKitKat(Intent intent) {
		imageUri = intent.getData();
		imagePath = getImagePath(imageUri, null);
		if (isClickCamera==false)
		{
			File oldFile = null;
			try {
				oldFile = FileUtil.getTempFile(PopupSelectImage.this, imageUri);
			}catch (Exception e){}
			resultIntent.putExtra("file",setbitmaps(oldFile));// new File(imagePath));
//			resultIntent.putExtra("file", new File(imagePath));
			/**
			 * dsy 为了判断是否是点击了拍照 false代表是相册 true代表相机
			 */
			setResult(RESULT_OK, resultIntent);
			//Toast.makeText(this, "设置成功"+path, Toast.LENGTH_SHORT).show();
			finish();
		}
	}

	private String getImagePath(Uri uri, String selection) {
		String path = null;
		//通过Uri和selection老获取真实的图片路径
		Cursor cursor = getContentResolver().query(uri, null, selection, null, null);
		if (cursor != null) {
			if (cursor.moveToFirst()) {
				path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
			}
			cursor.close();
		}
		return path;
	}

}